package cn.zm.app.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.PathParam;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.zm.app.pojo.AppCategory;
import cn.zm.app.pojo.AppInfo;
import cn.zm.app.pojo.AppVersion;
import cn.zm.app.pojo.DataDictionary;
import cn.zm.app.pojo.DevUser;
import cn.zm.app.service.CategoryService;
import cn.zm.app.util.Page;

import com.alibaba.fastjson.JSONArray;

@Controller
@RequestMapping("category")
public class CategoryController {

	@Resource
	private CategoryService categoryService;

	/*
	 * 开发者登陆成功 app页面维护 的页面加载方法c
	 */
	@RequestMapping("/tolist")
	public String tolist(HttpSession session, Model model) {
		// 所属平台
		List<DataDictionary> ddtList1 = categoryService.dictionaryList1();
		// App状态
		List<DataDictionary> ddtList2 = categoryService.dictionaryList2();
		// 一级目录
		List<AppCategory> category1 = categoryService.categoryList1();
		// 二级目录
		List<AppCategory> category2 = categoryService.categoryList2();
		// 三级目录
		List<AppCategory> category3 = categoryService.categoryList3();

		session.setAttribute("statusList", ddtList2);
		session.setAttribute("flatFormList", ddtList1);
		session.setAttribute("categoryLevel1List", category1);
		session.setAttribute("categoryLevel2List", category2);
		session.setAttribute("categoryLevel3List", category3);

		DevUser devUser = (DevUser) session.getAttribute("devUserSession");
		if (null == devUser) {
			model.addAttribute("error", "请先登录！！");
			return "jsp/devlogin";
		}
		String devId = devUser.getId().toString();

		// 分页查询
		selectList(null, null, null, null, null, null, devId, 1, 5, session);

		return "jsp/developer/appinfolist";
	}

	// 分页查询方法
	public void selectList(String softwareName, String status,
			String categoryLevel1, String categoryLevel2,
			String categoryLevel3, String flatformId, String devId,
			int currentPageNo, int pageSize, HttpSession session) {
		Page page = new Page();
		int countNumbs = categoryService.selectCount(softwareName, status,
				categoryLevel1, categoryLevel2, categoryLevel3, flatformId,
				devId);
		page.setPageSize(pageSize);
		page.setCurrentPageNo(currentPageNo);
		page.setTotalCount(countNumbs);
		int numbs = (currentPageNo - 1) * pageSize;
		List<AppInfo> cateList = categoryService.appInfoList(softwareName,
				status, categoryLevel1, categoryLevel2, categoryLevel3,
				flatformId, devId, numbs, pageSize);

		session.setAttribute("pages", page);
		session.setAttribute("appInfoList", cateList);

	}

	/*
	 * 查询和上下页 查询方法
	 */
	@RequestMapping("/doList")
	public String dolist(@RequestParam("querySoftwareName") String name,
			@RequestParam("queryStatus") String status,
			@RequestParam("queryCategoryLevel1") String categoryLevel1,
			@RequestParam("queryCategoryLevel2") String categoryLevel2,
			@RequestParam("queryCategoryLevel3") String categoryLevel3,
			@RequestParam("queryFlatformId") String formId,
			@RequestParam("pageIndex") String pageIndex, HttpSession session,
			Model model) {

		DevUser devUser = (DevUser) session.getAttribute("devUserSession");
		if (null == devUser) {
			model.addAttribute("error", "请先登录！！");
			return "jsp/devlogin";
		}
		String devId = devUser.getId().toString();

		// 分页查询
		int num = 0;
		if (null == pageIndex || pageIndex == "") {

		} else
			num = Integer.parseInt(pageIndex);

		selectList(name, status, categoryLevel1, categoryLevel2,
				categoryLevel3, formId, devId, num, 5, session);
		// 回调参数赋值
		model.addAttribute("querySoftwareName", name);
		model.addAttribute("queryStatus", status);
		model.addAttribute("queryCategoryLevel1", categoryLevel1);
		model.addAttribute("queryCategoryLevel2", categoryLevel2);
		model.addAttribute("queryCategoryLevel3", categoryLevel3);
		model.addAttribute("queryFlatformId", formId);

		return "jsp/developer/appinfolist";
	}

	/*
	 * 一级联动方法
	 */
	@ResponseBody
	@RequestMapping("/shangji1")
	public Object liandong1(@RequestParam("pid") String pid, HttpSession session) {
		List<String> pids = new ArrayList<String>();
		pids.add(pid);
		List<AppCategory> erji = categoryService.linkage1(pids);

		pids.clear();
		// 查询三级目录
		for (int i = 0; i < erji.size(); i++) {
			pids.add(erji.get(i).getId().toString());
		}
		List<AppCategory> sanji = categoryService.linkage1(pids);
		session.setAttribute("categoryLevel3List", sanji);

		return JSONArray.toJSONString(erji);
	}

	/*
	 * 二级联动方法
	 */
	@ResponseBody
	@RequestMapping("/shangji2")
	public Object liandong2(@RequestParam("pid") String pid, Model model) {
		List<String> pids = new ArrayList<String>();
		pids.add(pid);
		List<AppCategory> sanji = categoryService.linkage1(pids);

		pids.clear();
		// 查询上级目录
		List<AppCategory> yiji = categoryService.linkage2(pid);
		model.addAttribute("queryCategoryLevel1", yiji);

		return JSONArray.toJSONString(sanji);
	}

	/*
	 * 新增appTnfo
	 */
	@RequestMapping("/toaddApp")
	public String toaddApp(
			AppInfo appinfo,
			HttpSession session,
			Model model,
			@RequestParam(value = "a_logoPicPath", required = false) MultipartFile attach,
			HttpServletRequest request) {

		DevUser devUser = (DevUser) session.getAttribute("devUserSession");
		if (null == devUser) {
			model.addAttribute("error", "请先登录！！");
			return "jsp/devlogin";
		}

		String idLoPath = null;
		String fileName = null;
		String path = null;
		String path2 = null;
		String idPicPath = null;
		if (!attach.isEmpty()) {
			// 绝对路径
			path2 = request.getSession().getServletContext()
					.getRealPath("statics" + File.separator + "uploadfiles");
			// 相对路径
			path = request.getSession().getServletContext().getContextPath()
					+ File.separator + "statics" + File.separator
					+ "uploadfiles" + File.separator;
			System.out.println("uploadFile path得到当前路径======" + path);

			String oldFileName = attach.getOriginalFilename(); // 原文件名
			System.out.println("uploadFile oldName原文件名称=====" + oldFileName);

			String suffix = FilenameUtils.getExtension(oldFileName); // 得到原文件的后缀
			System.out.println("得到原文件的后缀名称=======" + suffix);
			int filesize = 5000000;

			if (attach.getSize() > filesize) { // 上传文件大小不得超过500kb
				request.setAttribute("fileUploadError", "上传文件的大小不能超过50000");
				return "jsp/developer/appinfoadd";
			} else if (suffix.equalsIgnoreCase("jsp")
					|| suffix.equalsIgnoreCase("png")
					|| suffix.equalsIgnoreCase("jpeg")
					|| suffix.equalsIgnoreCase("pneg")) {
				// 上传的图片格式不正确
				fileName = System.currentTimeMillis()
						+ RandomUtils.nextInt(10000) + "_personal.jpg";
				System.out.println("新的文件名称======" + fileName);

				File targetFile = new File(path2, fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				// 保存
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					request.setAttribute("fileUploadError", "文件上传失败");
					return "jsp/developer/appinfoadd";
				}
				idPicPath = path + fileName;
				idLoPath = path2 + File.separator + fileName;
				System.out.println("idPicPath=======" + idPicPath);

			} else {
				request.setAttribute("fileUploadError", "上传图片格式不正确");
				return "jsp/developer/appinfoadd";
			}
			// 判断文件是否为空

			appinfo.setDevId(devUser.getId());
			appinfo.setCreatedBy(1);
			appinfo.setCreationDate(new Date());
			appinfo.setLogoPicPath(idPicPath);
			appinfo.setLogoLocPath(idLoPath);

			if (categoryService.toaddAppInfo(appinfo) == 0) {
				model.addAttribute("fileUploadError", "新增失败！");
				return "jsp/developer/appinfoadd";
			}
		}
		return "redirect:/category/tolist";
	}

	/*
	 * 加载所属平台
	 */
	@ResponseBody
	@RequestMapping("/toaddSSPT")
	public Object toaddSSPT() {
		// 所属平台
		List<DataDictionary> ddtList1 = categoryService.dictionaryList1();
		return JSONArray.toJSONString(ddtList1);
	}

	/*
	 * 加载一级分类
	 */
	@ResponseBody
	@RequestMapping("/toaddYJFL")
	public Object toaddYJFL() {
		// 一级目录
		List<AppCategory> category1 = categoryService.categoryList1();
		return JSONArray.toJSONString(category1);
	}

	/*
	 * 加载二级分类
	 */
	@RequestMapping("/toaddEJML")
	@ResponseBody
	public Object toaddEJML(@RequestParam("pid") String pid) {
		List<String> pids = new ArrayList<String>();
		List<AppCategory> erji = new ArrayList<AppCategory>();
		if (null == pid || "" == pid) {
			erji = categoryService.categoryList1();
		} else {
			pids.add(pid);
			erji = categoryService.linkage1(pids);
		}

		return JSONArray.toJSONString(erji);
	}

	/*
	 * 加载三级分类
	 */
	@RequestMapping("/toaddSJML")
	@ResponseBody
	public Object toaddSJML(@RequestParam("pid") String pid) {
		List<String> pids = new ArrayList<String>();
		pids.add(pid);
		List<AppCategory> sanji = categoryService.linkage1(pids);

		return JSONArray.toJSONString(sanji);
	}

	/*
	 * 判断APKName是否存在
	 */
	@RequestMapping("/toValidateName")
	@ResponseBody
	public Object toValidateName(@RequestParam("APKName") String APKName) {
		Map<String, String> apps = new HashMap<String, String>();
		if (null == APKName || APKName == "") {
			apps.put("APKName", "empty");
		} else {
			AppInfo app = categoryService.toValidateName(APKName);
			if (null == app)
				apps.put("APKName", "noexist");
			else
				apps.put("APKName", "exist");
		}
		return JSONArray.toJSONString(apps);
	}

	/*
	 * 加载修改页面
	 */
	@RequestMapping("/appinfomodify")
	public String appinfomodify(
			@RequestParam(value = "id", required = false) int id,
			@RequestParam(value = "fileUploadError2", required = false) String fileUploadError2, Model model,
			HttpSession session) {
		DevUser devUser = (DevUser) session.getAttribute("devUserSession");
		if (null == devUser) {
			model.addAttribute("error", "请先登录！！");
			return "jsp/devlogin";
		}
		AppInfo app = categoryService.selectbyId(id);
		model.addAttribute("appInfo", app);
		return "jsp/developer/appinfomodify";
	}

	/*
	 * 修改后提交
	 */
	@RequestMapping("/appinfomodifysave")
	public String appinfomodifysave(AppInfo app, Model model) {
		int a = categoryService.updatebyId(app);
		if (a == 0) {
			return "redirect:/category/tolist";
		}
		model.addAttribute("fileUploadError2", "修改 失败678！！");
		model.addAttribute("id", app.getId());
		return "forward:/category/appinfomodify";
	}
	
	/*
	 * 查询版本信息
	 */
	@RequestMapping("/appversionadd")
	public String appversionadd(@RequestParam(value="id") int id, Model model,HttpServletRequest request) {
		System.out.println("====================="+id);
		List<AppVersion> appvs = categoryService.viewAppVersions(id+"");
		model.addAttribute("appVersionList", appvs);
		model.addAttribute("id", id);
		return "/jsp/developer/appversionadd";
	}

	/*
	 * 新增版本信息
	 */
	/*@Transactional(rollbackFor=RuntimeException.class)
	@RequestMapping("/addversionsave2")
	public String addversionsave(AppVersion av, HttpSession session,
			HttpServletRequest request,Model model) {
		System.out.println("---------------------------"+av.getAppId());
		return "forward:/category/appversionadd?id="+av.getAppId();
	}
	*/
	
	@Transactional(rollbackFor=RuntimeException.class)
	@RequestMapping("/addversionsave")
	public String addversionsave2(AppVersion av, HttpSession session,
			HttpServletRequest request,Model model,
			@RequestParam(value = "a_downloadLink") MultipartFile attach) {
		 
		DevUser du= (DevUser) session.getAttribute("devUserSession");
		int createdby=du.getId();
		
		av.setCreatedBy(createdby);

		String idPicPath = null; // 绝对路径+新的文件名称
		String idLoPath = null; // 相对路径+新的文件名称
		String fileName = null; // 新的文件名称
		String path = null; // 相对路径
		String path2 = null; // 绝对路径
		if (!attach.isEmpty()) {
			// 绝对路径
			path2 = request.getSession().getServletContext()
					.getRealPath("statics" + File.separator + "uploadfiles");
			// 相对路径
			path = request.getSession().getServletContext().getContextPath()
					+ File.separator + "statics" + File.separator
					+ "uploadfiles" + File.separator;
			System.out.println("uploadFile path得到当前路径======" + path);
			// 原文件名
			String oldFileName = attach.getOriginalFilename();
			System.out.println("uploadFile oldName原文件名称=====" + oldFileName);
			// 得到原文件的后缀
			String suffix = FilenameUtils.getExtension(oldFileName);
			System.out.println("得到原文件的后缀名称=======" + suffix);

			int filesize = 5000000;
			if (attach.getSize() > filesize) { // 上传文件大小不得超过500kb
				request.setAttribute("fileUploadError", "上传文件的大小不能超过50000");
			} else if (suffix.equalsIgnoreCase("apk")
					|| suffix.equalsIgnoreCase("jpg")
					|| suffix.equalsIgnoreCase("txt")
					|| suffix.equalsIgnoreCase("png")) {
				// 生成新文件路径
				fileName = System.currentTimeMillis()
						+ RandomUtils.nextInt(10000) + "_personal.jpg";
				System.out.println("新的文件名称======" + fileName);

				File targetFile = new File(path2, fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				// 保存
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					request.setAttribute("fileUploadError", "文件上传失败");					
				}
				idPicPath = path + fileName;
				idLoPath = path2 + File.separator + fileName;
				System.out.println("idPicPath=======" + idPicPath);
				av.setDownloadLink(idLoPath);
				av.setApkLocPath(idPicPath);
				av.setApkFileName(fileName);
				av.setCreationDate(new Date());
				int a = categoryService.addAppVersion(av);
				if(a>0){
					int b=categoryService.viewAppVersionId(av.getAppId().toString());
					int c=categoryService.modifyAppVersionId(av.getAppId().toString(),b+"");					
					return "forward:/category/appversionadd?id="+av.getAppId();
				}
			} else {
				request.setAttribute("fileUploadError", "上传图片格式不正确");
			}
		} 
		/*
		 * 此处可以添加回掉数据
		 */
		//model.addAttribute("id", av.getAppId().toString());
		return "forward:/category/appversionadd?id="+av.getAppId();
	}
	
	/*
	 * 修改版本信息显示
	 */
	@RequestMapping("/appversionmodify")	
	public String appversionmodify(@RequestParam("vid")String vid,
				@RequestParam("aid")String aid,Model model){
		List<AppVersion> appvs = categoryService.viewAppVersions(aid);
		model.addAttribute("appVersionList", appvs);
		AppVersion appv=categoryService.viewAppVersionById(vid);
		model.addAttribute("appVersion", appv);
		
		return "jsp/developer/appversionmodify";
	}

	/*
	 * 修改版本信息
	 */
	@RequestMapping("/appversionmodifysave")
	public String appversionmodifysave(AppVersion appver,HttpSession session,Model model){
		DevUser devUser = (DevUser) session.getAttribute("devUserSession");
		if (null == devUser) {
			model.addAttribute("error", "请先登录！！");
			return "jsp/devlogin";
		}

		appver.setModifyBy(devUser.getId());
		appver.setModifyDate(new Date());
		
		if(categoryService.modifyAppVersion(appver)==1){			
			return "redirect:/category/tolist";
		}		
		return "redirect:/category/appversionmodify?vid="+appver.getId()+"&aid="+appver.getAppId();
	}
	
	/*
	 * 查看版本信息
	 */
	@RequestMapping(value="/appview/{id}")
	public String appview(@PathVariable String id,Model model){
		List<AppVersion> appvs = categoryService.viewAppVersions(id);
		model.addAttribute("appVersionList", appvs);
		AppInfo app=categoryService.viewAppInfo(id);
		model.addAttribute("appInfo", app);
		
		return "jsp/developer/appinfoview";
	}
	
	/*
	 * 删除版本信息
	 */
	@RequestMapping("/delapp")
	@Transactional(rollbackFor=RuntimeException.class)
	@ResponseBody
	public Object delapp(String id){
		Map<String,String> delResult=new HashMap<String, String>();
		if(id==null){			
			delResult.put("delResult", "notexist");
		}else{
			try {
				categoryService.modifyAppVersion(id);
				categoryService.modifyAppInfo(id);
				delResult.put("delResult", "true");
			} catch (Exception e) {
				delResult.put("delResult", "false");
			}
		}
		return JSONArray.toJSONString(delResult);
	}
	
	
}
